package com.apes.framework.plugin.websocket;

import com.alibaba.fastjson.JSON;
import com.apes.framework.config.redis.RedisMessageListener;
import com.apes.framework.util.Tools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 功能：消息订阅者
 *
 * @author xul
 * @create 2018-06-30 17:38
 */
@Slf4j
@Component
public class WsSubscriber {

    @RedisMessageListener(topic = "ws:topic")
    public void onMessage(String message) {
        WsMessage wsMessage = Tools.toBean(WsMessage.class, (Map) JSON.parse(message));
        if (WsMessage.ALL_USER.equals(wsMessage.getTo())) {
            WebSocketServer.getWebSocketSet().stream().forEach(ws -> sendMessage(ws, wsMessage.getBody()));
        } else {
            WebSocketServer.getWebSocketSet().stream().filter(ws -> ws.getUserId().equalsIgnoreCase(wsMessage.getTo())).forEach(ws -> {
                sendMessage(ws, wsMessage.getBody());
            });
        }
    }

    private void sendMessage(WebSocketServer ws, String message) {
        try {
            ws.sendMessage(message);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

}
